package study.HL7.lis_hl7;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.app.HL7Service;
import ca.uhn.hl7v2.app.SimpleServer;
import ca.uhn.hl7v2.llp.LowerLayerProtocol;
import ca.uhn.hl7v2.llp.MinLowerLayerProtocol;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.parser.PipeParser;
import ca.uhn.hl7v2.protocol.ReceivingApplication;
import ca.uhn.hl7v2.protocol.ReceivingApplicationException;
import lombok.SneakyThrows;

import java.io.IOException;
import java.util.Map;

/**
 * @Author 刘伟涛
 * @Date 2024/8/6 15:15
 **/
public class HL7LLPServer {
    public static void main(String[] args) throws Exception {
// 设置监听端口
        int port = 8888;

        // 创建 Lower Layer Protocol 和 Parser
        LowerLayerProtocol llp = new MinLowerLayerProtocol(); // MinLowerLayerProtocol handles SB/EB/CR
        System.out.println(llp);
        PipeParser parser = new PipeParser();

        // 创建 SimpleServer
        SimpleServer server = new SimpleServer(port, llp, parser);

        // 创建接收应用
        ReceivingApplication<Message> app = new ReceivingApplication<Message>() {
            @Override
            public boolean canProcess(Message message) {
                return true; // 可以根据消息类型做进一步过滤
            }

            @SneakyThrows
            @Override
            public Message processMessage(Message message, Map<String, Object> metadata) {
                // 处理接收到的 HL7 消息
                System.out.println("Received message:\n" + message.encode());

                // 返回 ACK 响应
                return message.generateACK();
            }
        };

        // 注册接收应用
        server.registerApplication("*", "*", app);

        // 启动服务器
        server.start();

        System.out.println("HL7 Server is running on port " + port);
    }
}
